package com.crane.oss.school.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crane.common.core.dto.MultiResponse;
import com.crane.common.core.dto.Response;
import com.crane.common.core.dto.SingleResponse;
import com.crane.common.core.utils.CollectionUtil;
import com.crane.oss.app.bean.request.mqtt.UpdateModeResp;
import com.crane.oss.app.bean.request.mqtt.UpdateMusicModeReq;
import com.crane.oss.school.dao.EquipmentDao;
import com.crane.oss.school.dao.StudentDao;
import com.crane.oss.school.model.Equipment;
import com.crane.oss.school.model.Student;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crane.common.core.exception.AppException;
import com.crane.common.core.exception.BasicErrorCode;
import com.crane.common.core.exception.SysException;
import com.crane.common.core.utils.StringUtil;
import com.crane.common.framework.utils.BeanUtil;
import com.crane.oss.enums.BindStatusEnum;
import com.crane.oss.enums.UseStatusEnum;
import com.crane.oss.school.bean.request.QueryStudentEquipmentReq;
import com.crane.oss.school.bean.request.studentequipment.AddStudentEquipmentReq;
import com.crane.oss.school.bean.request.studentequipment.UpdateStudentEquipmentReq;
import com.crane.oss.school.bean.resp.StudentEquipmentIndexResp;
import com.crane.oss.school.bean.resp.StudentEquipmentResp;
import com.crane.oss.school.dao.StudentEquipmentDao;
import com.crane.oss.school.model.StudentEquipment;
import com.crane.oss.school.model.StudentEquipmentIndex;
import com.crane.oss.school.service.StudentEquipmentService;

import lombok.extern.slf4j.Slf4j;

/**
 *
 * @author zhenxing.pi
 * @email ccsu123456@qq.com
 * @date 2023年01月17日 23时03分27秒
 */
@Service
@Slf4j
public class StudentEquipmentServiceImpl implements StudentEquipmentService {

	@Resource
	protected StudentEquipmentDao studentEquipmentDao;

	@Resource
	EquipmentDao equipmentDao;

	@Resource
	StudentDao studentDao;

	@Override
	public StudentEquipmentResp queryStudentEquipment(Long id) {
		log.info("StudentEquipmentBOImpl queryStudentEquipment id={}", id);
		StudentEquipment studentEquipment = studentEquipmentDao.selectById(id);
		if (null == studentEquipment) {
			throw new AppException(BasicErrorCode.ENTITY_NOT_EXISTS, "studentEquipment");
		}
		StudentEquipmentResp studentEquipmentResp = new StudentEquipmentResp();
		BeanUtil.copyProperties(studentEquipment, studentEquipmentResp);
		return studentEquipmentResp;
	}

	@Override
	public List<StudentEquipmentIndexResp> queryEquipmentForIndex(Long studentId) {
		log.info("StudentEquipmentBOImpl queryEquipmentForIndex studentId={}", studentId);
		List<StudentEquipmentIndexResp> respList = new ArrayList<StudentEquipmentIndexResp>();
		List<StudentEquipmentIndex> query = studentEquipmentDao.queryEquipmentForIndex(studentId);
		for (StudentEquipmentIndex index : query) {
			StudentEquipmentIndexResp resp = new StudentEquipmentIndexResp();
			resp.setName(index.getOldName());
			if (StringUtil.isNotBlank(index.getNewName())) {
				resp.setName(index.getNewName());
			}
			BeanUtil.copyProperties(index, resp);
			resp.setUseStatusName(UseStatusEnum.getUseStatusName(index.getUseStatus()));
			resp.setBindStatusName(BindStatusEnum.getBindStatusName(index.getBindStatus()));
			respList.add(resp);
		}
		return respList;
	}

	@Override
	public Response bindEquiment(Long studentId, String imei) {
		Student student=studentDao.selectById(studentId);
		if(null == student){
			return Response.buildFailure("学生不存在");
		}
		Equipment equipment=null;
		Equipment dbEquipment=equipmentDao.selectOne(Wrappers.lambdaQuery(Equipment.class).eq(Equipment ::getImei,imei));
		if(null == dbEquipment){
			Equipment addEquipment=new Equipment();
			addEquipment.setPartyId(student.getPartyId());
			addEquipment.setSchoolId(student.getSchoolId());
			addEquipment.setName("跳绳设备"+imei);
			addEquipment.setType(1);
			addEquipment.setModel("");
			addEquipment.setNetwork("物联网");
			addEquipment.setImei(imei);
			addEquipment.setImsi("");
			addEquipment.setVersion("");
			addEquipment.setMusicMode(1);
			addEquipment.setSkipmode(1);
			addEquipment.setStatus(1);
			addEquipment.setCreateTime(new Date());
			addEquipment.setUpdateTime(new Date());
			equipmentDao.insert(addEquipment);
			equipment=addEquipment;
		}else{
			equipment=dbEquipment;
		}
		if(!equipment.getStatus().equals(1)){
			return Response.buildFailure("设备状态不可用");
		}

		List<StudentEquipment> studentEquipmentList=studentEquipmentDao.selectList(Wrappers.lambdaQuery(StudentEquipment.class)
				.eq(StudentEquipment ::getEquipmentId,equipment.getEquipmentId()));
		if(CollectionUtil.isNotEmpty(studentEquipmentList)){
            for(StudentEquipment studentEquipment : studentEquipmentList){
            	if(studentEquipment.getStudentId().equals(studentId)){
            		if(!studentEquipment.getBindStatus().equals(1)){
						studentEquipment.setBindStatus(1);
						studentEquipment.setBindTime(new Date());
						studentEquipmentDao.updateById(studentEquipment);
					}else{
						return Response.buildFailure("您已绑定该跳绳，请勿重复绑定");
					}
				}else{
					return Response.buildFailure("此跳绳已被其他用户绑定，请勿重复绑定");
				}
			}
		}else{
			StudentEquipment addStudentEquipment=new StudentEquipment();
			addStudentEquipment.setStudentId(studentId);
			addStudentEquipment.setEquipmentId(equipment.getEquipmentId());
			addStudentEquipment.setName(equipment.getName());
			addStudentEquipment.setBindType(1);
			addStudentEquipment.setBindStatus(1);
			addStudentEquipment.setUseStatus(1);
			addStudentEquipment.setBindTime(new Date());
			addStudentEquipment.setCreateTime(new Date());
			addStudentEquipment.setUpdateTime(new Date());
			studentEquipmentDao.insert(addStudentEquipment);
		}
		return Response.buildSuccess();
	}

	@Override
	public Response unBindEquiment(Long studentId, String imei) {
		Equipment dbEquipment=equipmentDao.selectOne(Wrappers.lambdaQuery(Equipment.class).eq(Equipment ::getImei,imei));
		if(null == dbEquipment){
			return Response.buildFailure("设备不存在");
		}
		dbEquipment.setMusicMode(1);
		equipmentDao.updateById(dbEquipment);
		List<StudentEquipment> studentEquipmentList=studentEquipmentDao.selectList(Wrappers.lambdaQuery(StudentEquipment.class)
				.eq(StudentEquipment ::getEquipmentId,dbEquipment.getEquipmentId()));
		if(CollectionUtil.isNotEmpty(studentEquipmentList)){
			for(StudentEquipment studentEquipment : studentEquipmentList){
				if(studentEquipment.getStudentId().equals(studentId)){
					if(studentEquipment.getBindStatus().equals(1)){
						studentEquipmentDao.deleteById(studentEquipment.getSeId());
						return Response.buildSuccess();
					}
				}
			}
		}
		return Response.buildFailure("不存在绑定关系");
	}

	@Override
	public MultiResponse<UpdateModeResp> musicModeRope(Long studentId, int musicMode) {
		List<StudentEquipment> studentEquipmentList=studentEquipmentDao.selectList(Wrappers.lambdaQuery(StudentEquipment.class)
				.eq(StudentEquipment ::getStudentId,studentId));
		List<UpdateModeResp> resps=new ArrayList<>();
		if(CollectionUtil.isNotEmpty(studentEquipmentList)){
			for(StudentEquipment studentEquipment : studentEquipmentList){
				Equipment dbEquipment=equipmentDao.selectById(studentEquipment.getEquipmentId());
				dbEquipment.setMusicMode(musicMode);
				equipmentDao.updateById(dbEquipment);
				UpdateModeResp resp=new  UpdateModeResp();
				resp.setBindType(studentEquipment.getBindType());
				resp.setImei(dbEquipment.getImei());
				resps.add(resp);
			}
		}
		return MultiResponse.ofWithoutTotal(resps);
	}

	@Override
	public  MultiResponse<UpdateModeResp> skipModeRope(Long studentId, int skipmode) {
		List<StudentEquipment> studentEquipmentList=studentEquipmentDao.selectList(Wrappers.lambdaQuery(StudentEquipment.class)
				.eq(StudentEquipment ::getStudentId,studentId));
		List<UpdateModeResp> resps= new ArrayList<>();
		if(CollectionUtil.isNotEmpty(studentEquipmentList)){
			for(StudentEquipment studentEquipment : studentEquipmentList){
				Equipment dbEquipment=equipmentDao.selectById(studentEquipment.getEquipmentId());
				dbEquipment.setSkipmode(skipmode);
				equipmentDao.updateById(dbEquipment);
				UpdateModeResp resp=new  UpdateModeResp();
				resp.setBindType(studentEquipment.getBindType());
				resp.setImei(dbEquipment.getImei());
				resps.add(resp);
			}
		}
		return MultiResponse.ofWithoutTotal(resps);
	}

	@Override
	public Integer queryEquipmentMusicMode(Long studentId) {
		List<StudentEquipment> studentEquipmentList=studentEquipmentDao.selectList(Wrappers.lambdaQuery(StudentEquipment.class)
				.eq(StudentEquipment ::getStudentId,studentId));
		if(CollectionUtil.isEmpty(studentEquipmentList)){
			return null;
		}
		Equipment dbEquipment=equipmentDao.selectById(studentEquipmentList.get(0).getEquipmentId());
		return dbEquipment.getMusicMode();
	}

	@Override
	public IPage<StudentEquipmentResp> queryList(QueryStudentEquipmentReq queryRequest) {
		log.info("StudentEquipmentBOImpl queryList queryRequest={}", queryRequest);
		IPage<StudentEquipmentResp> result = new Page<>();
		result.setCurrent(queryRequest.getPageNo());
		result.setPages(queryRequest.getPageSize());

		LambdaQueryWrapper<StudentEquipment> queryStudentEquipmentWrapper = new LambdaQueryWrapper<>();
		IPage<StudentEquipment> page = studentEquipmentDao.selectPage(
				new Page<>(queryRequest.getPageNo(), queryRequest.getPageSize()), queryStudentEquipmentWrapper);
		return page.convert(u -> {
			StudentEquipmentResp v = new StudentEquipmentResp();
			BeanUtils.copyProperties(u, v);
			return v;
		});
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int save(AddStudentEquipmentReq addRequest) {
		log.info("StudentEquipmentBOImpl save request={}", addRequest);
		StudentEquipment studentEquipment = new StudentEquipment();
		BeanUtil.copyProperties(addRequest, studentEquipment);
		int i = 0;
		try {
			i = studentEquipmentDao.insert(studentEquipment);
		} catch (Exception e) {
			log.info("StudentEquipmentBOImpl add e={}", e);
			throw new SysException();
		}
		return i;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int update(UpdateStudentEquipmentReq updateRequest) {
		log.info("StudentEquipmentServiceImpl update request={}", updateRequest);
		StudentEquipment queryStudentEquipment = studentEquipmentDao.selectById(updateRequest.getSeId());
		if (null == queryStudentEquipment) {
			throw new AppException(BasicErrorCode.DEFINED_MSG, "该设备未绑定");
		}
		Equipment dbEquipment=equipmentDao.selectById(queryStudentEquipment.getEquipmentId());
		StudentEquipment updateStudentEquipment = new StudentEquipment();
		updateStudentEquipment.setSeId(updateRequest.getSeId());
		int i = 0;
		try {
			if (StringUtil.isNotBlank(updateRequest.getName())) {
				updateStudentEquipment.setName(updateRequest.getName());
			}
			if (StringUtil.isNotBlank(updateRequest.getBindStatus())) {
				updateStudentEquipment.setBindStatus(Integer.valueOf(updateRequest.getBindStatus()));
			}
			if (StringUtil.isNotBlank(updateRequest.getUseStatus())) {
				updateStudentEquipment.setUseStatus(Integer.valueOf(updateRequest.getUseStatus()));
			}
			updateStudentEquipment.setUpdateTime(new Date());
			i = studentEquipmentDao.updateById(updateStudentEquipment);
		} catch (Exception e) {
			log.info("StudentEquipmentServiceImpl update e={}", e);
			throw new SysException();
		}
		return i;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int delete(Long id) {
		log.info("StudentEquipmentServiceImpl delete id={}", id);
		return studentEquipmentDao.deleteById(id);
	}

}
